/*
 * Created on Sun Oct 01 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import Router from 'koa-router';
import { 
  createSucceedBody,
} from '../utils/BodyUtils';
import {
  createError
} from '../utils/ErrorUtils.js';

import multer from 'koa-multer';
import config from '../config';
import fse from 'fs-extra';
import uuidv1 from 'uuid/v1';
import { ErrorCode } from '../constants';
import { authenticationMiddleware } from '../utils/TokenUtils';
import hasha from 'hasha';
import FileService from '../services/file';
import send from 'koa-send';
import URI from 'urijs';

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, config.path.tmpUploadDir);          
  },
  filename: (req, file, cb) => {
    cb(null, uuidv1());
  }
});
const upload = multer({ storage: storage });

const router = new Router();

router.post('/', authenticationMiddleware,  upload.single('file'),  async (ctx) => {
  //注意multer是将body file注入到ctx.req对象上 而不是ctx.request对象上
  /* eslint-disable no-unused-vars*/
  var file = ctx.req.file;
  var body = ctx.req.body;

  if (file != null) {
    let md5 = await hasha.fromFile(file.path, { algorithm: 'md5' });
    let result = await FileService.upload({
      path: file.path,
      mimeType: file.mimetype, 
      md5: md5
    });

    let url = '';
    let uri = new URI(result.uri);
    
    if (uri.protocol() === 'file') {
      //file uri
      url = ctx.origin + ctx.path + '/' + result.fid;
    } else {
      url = result.uri;
    }

    ctx.response.status = 200;    
    ctx.response.body = createSucceedBody('上传成功', {
      url: url
    });

  } else {
    throw createError(400, '上传失败', ErrorCode.UPLOAD_FAIL);
  }
});

router.get('/:fid', async (ctx) => {
  let result = await FileService.getFile({ fid: ctx.params.fid });
  let uri = new URI(result.uri);
  if (uri.protocol() === 'file') {
    //file uri
    let path = uri.path();
    await send(ctx, path, { root: '/' });
    ctx.response.type = result.mimeType; 
  } else {
    throw createError(400, 'URI不支持', ErrorCode.FILE_NOT_FOUNT);    
  }
});

export default router;


